package com.bbs2.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.bbs2.entity.User;
import com.bbs2.util.DBHelp;
import com.bbs2.util.RowMapper;

public class UserDao {
	private DBHelp<User> db = new DBHelp<User>();
	public User findByNameAndPwd(String name,String pwd){
		String sql = "SELECT id,NAME,PASSWORD,regTime,email,flag,pic FROM t_user where name=? and password=?";
		return db.queryForObject(sql, new UserMap(), name,pwd);
	}
	public User findByName(String name){
		String sql = "SELECT id,NAME,PASSWORD,regTime,email,flag,pic FROM t_user where name=?";
		return db.queryForObject(sql, new UserMap(), name);
	}
	public int save(User user) {
		String sql = "INSERT INTO t_user(NAME,PASSWORD,email,flag,pic,regTime) VALUES(?,?,?,?,?,?)";
		return db.executeUpdate(sql, user.getName(),user.getPassword(),user.getEmail(),user.getFlag(),user.getPic(),user.getRegTime());
	}
	public User findById(String id){
		String sql = "SELECT id,NAME,PASSWORD,regTime,email,flag,pic FROM t_user where id=?";
		return db.queryForObject(sql, new UserMap(), id);
	}
	public int del(String id){
		String sql = "DELETE FROM t_user WHERE id=?";
		return db.executeUpdate(sql, id);
	}
	public List<User> findAll(){
		String sql = "SELECT id,NAME,PASSWORD,regTime,email,flag,pic FROM t_user where flag=1";
		return db.queryForList(sql, new UserMap());
	}
	public int update(User user){
		String sql = "UPDATE t_user SET NAME=?,PASSWORD=?,email=?,flag=?,pic=? WHERE id=?";
		return db.executeUpdate(sql, user.getName(),user.getPassword(),user.getEmail(),user.getFlag(),user.getPic(),user.getId());
	}
}
class UserMap implements RowMapper<User>{

	public User mapRow(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("id"));
		user.setName(rs.getString("name"));
		user.setPassword(rs.getString("password"));
		user.setRegTime(rs.getString("regTime"));
		user.setEmail(rs.getString("email"));
		user.setFlag(rs.getInt("flag"));
		user.setPic(rs.getString("pic"));
		return user;
	}
	
}